package com.itinsys.enma.dao.impl;

import java.util.List;

import net.sf.ehcache.ObjectExistsException;

import org.apache.log4j.Logger;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.type.Type;

import com.itinsys.enma.dao.DBTemplate;
import com.itinsys.enma.dao.UserDAO;
import com.itinsys.enma.dao.hibernate.DBObject;
import com.itinsys.enma.domain.User;


public class UserDAOImpl implements UserDAO {

	
	private static Logger logger = Logger.getLogger(UserDAOImpl.class);

	
	public void addUserRole(User userR) {
		// TODO Auto-generated method stub
		
	}

	@SuppressWarnings("unchecked")
	public List<User> listUsers() {
		Session sess = null;
		List<User> result = null;
		try {
			sess = DBTemplate.getConnTemplate().getSessionFactory().openSession();
			Query query = sess.createQuery("from u in class com.itinsys.enma.domain.User where active=? order by u.username");
			query.setParameters(new Object[] { true }, new Type[] {	Hibernate.BOOLEAN });
			result = query.list();
			if (result.isEmpty()) {
				throw new ObjectExistsException("No se encontraron usuarios ");
			}
		} catch (HibernateException e) {
			logger.error("Error al buscar usuarios", e);
		} finally {
			if (sess != null) {
				sess.close();
			}

		}
		return result;
	}

	
	
	@SuppressWarnings("unchecked")
	public User getByUserName(String userName, boolean active)
			throws ObjectExistsException {
		Session sess = null;
		List<User> result = null;
		try {
			sess = DBTemplate.getConnTemplate().getSessionFactory().openSession();
			Query query = sess.createQuery("from u in class com.itinsys.enma.domain.User where username=? and active=?");
			query.setParameters(new Object[] { userName, active }, new Type[] {	Hibernate.STRING, Hibernate.BOOLEAN });
			result = query.list();
			if (result.isEmpty()) {
				throw new ObjectExistsException("Usuario sin rol asignado.");
			}
		} catch (HibernateException e) {
			logger.error("Error al buscar usuario por ID: " + userName, e);
		} finally {
			if (sess != null) {
				sess.close();
			}

		}
		return result.get(0);
	}

	@Override
	public void add(User u) {
		DBObject.addObject(u);
	}

	@Override
	public boolean updateUser(User user) {
		
		return DBObject.updateObject(user);
	}

}